package cn.freeprogrammer.igen.generator;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import cn.freeprogrammer.igen.Globals;
import cn.freeprogrammer.igen.data.EntityData;
import cn.freeprogrammer.igen.data.ProjectData;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

/**
 * Entity生成器.
 * 
 * @author minwh
 *
 */
public class EntityGenerator implements IGenerator {
	private ProjectData projectData;
	private Template tpl;

	public EntityGenerator(ProjectData projectData) throws Exception {
		this.projectData = projectData;
		
		// load sqlmap template
		Configuration cfg = new Configuration();
		cfg.setDirectoryForTemplateLoading(new File(getClass().getResource(Globals.TPL_DIRECTORY)
				.getFile()));
		cfg.setObjectWrapper(new DefaultObjectWrapper());
		tpl = cfg.getTemplate(Globals.ENTITY_TPL);
		
		// create dao base dir
		new File(projectData.getEntityBasePath()).mkdirs();
	}	
	
	public void generate() throws Exception {
		if (!projectData.isGenerateEntity()) {
			return;
		}
		
		for (EntityData entityData : projectData.getEntityDatas()) {
			generate(entityData);
		}
	}

	private void generate(EntityData entityData) throws Exception {
		Map model = new HashMap();
		model.put("metadata", entityData);

		String filePath = getEntityFilePath(entityData);
		File file = new File(filePath);
		file.getParentFile().mkdirs();
		file.createNewFile();
		
		Writer out = new FileWriter(file);
		tpl.process(model, out);
		out.flush();
	}

	private String getEntityFilePath(EntityData entityData) {
		String entityFilePath = projectData.getEntityBasePath() + "/"
				+ entityData.getFullEntityName().replaceAll("\\.", "/") + ".java";
		return entityFilePath;
	}
}
